#!/bin/bash

namedConf=/etc/bind/named.conf
resolvConf=/etc/resolv.conf
bind=/etc/init.d/bind9
bindPath=/etc/bind

function desinstalarServer {
    echo "Limpiando archivos directorio ${bindPath}..."
    rm -rf "${bindPath}"/*

    echo "Deteniendo bind9..."

    pkill named
    service bind9 stop
    #bash ${bind} stop
}

function desinstalarHost {
    echo "Limpiando ${resolvConf}"
    echo "" > ${resolvConf}
}

function configurarRoot {

    desinstalarServer
    echo "Creando directorio ${bindPath}..."
    mkdir -p ${bindPath}

    echo "Creando ${namedConf}..."
    cp -f root/named.conf.root ${namedConf};

    echo "Copiando archivos de base de datos..."
    cp root/db.* "${bindPath}"
    chmod 777 -R ${bindPath}

    echo "Reiniciando bind9..."
    service bind9 start
}

function configurarDNS1 {
   
    desinstalarServer
    echo "Creando directorio ${bindPath}..."
    mkdir -p ${bindPath}

    echo "Creando ${namedConf}..."
    cp -f cataratas/cataratas.named.conf ${namedConf};

    echo "Copiando archivos de base de datos..."
    cp cataratas/db.* "${bindPath}"
    chmod 777 -R ${bindPath}
    
    echo "Reiniciando bind9..."
    service bind9 start
}

function configurarDNS2 {
   
    desinstalarServer
    echo "Creando directorio ${bindPath}..."
    mkdir -p ${bindPath}

    echo "Creando ${namedConf}..."
    cp -f resto/resto.named.conf ${namedConf};

    echo "Copiando archivos de base de datos..."
    cp -f resto/db.* "${bindPath}"
    chmod 777 -R ${bindPath}
    
    echo "Reiniciando bind9..."
    service bind9 start
}

function configurarHost {
    echo "Haciendo backup de ${resolvConf}..."
    mv "${resolvConf}" "${resolvConf}.${timestamp}"

    echo "Actualizando ${resolvConf}..."
    cp "resolv.conf.$1" "${resolvConf}"
    chmod a+r "${resolvConf}"
}

case "${1}" in
    principal)
	configurarRoot
	;;
    
    cataratas)
	configurarDNS1
	;;
    
    resto)
	configurarDNS2
	;;
    
    host)
        configurarHost $2
	;;
    
    cleanserv)
	desinstalarServer;
	;;

    cleanhost)
	desinstalarHost;
	;;

    *)
	echo 'error: opcion invalida'
	help
	;;
esac
